<?php

namespace app\api\controller;

use app\common\model\Comment;
use app\common\validate\Comment as CommentValidate;
use app\common\controller\Api;
use app\common\model\TeacherJob as TeacherJobModel;
use app\common\model\StaffOrder as StaffOrderModel;
use think\Db;

class StaffOrder extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    //家教支持押金接单
    public function add()
    {
        $params = $this->request->post();

        //todo 测试接单不需要是老师也能接单
//        $teacher = Db::name('teacher')->where([
//            'user_id' => $this->auth->id,
//            'deletetime' => Db::raw('deletetime IS NULL')
//        ])->find();
//        if(!$teacher){
//            $this->error('请先入驻成为家教再进行操作');
//        }

        $teacher_job_info = Db::name('teacher_job')->where([
            'id' => $params['job_id'],
        ])->find();
        if(!$teacher_job_info){
            $this->error('数据错误!');
        }

        $already_apply = Db::name('staff_order')->where([
            'user_id' => $this->auth->id,
            'job_id' => $params['job_id'],
            'status' => ['in','1,2,3']
        ])->find();
        if($already_apply){
            $this->error('您已报名该次急招请勿重复操作');
        }

        $order = StaffOrderModel::addOrder($params);
        $this->success('订单添加成功', $order);
    }

    //家教接单列表
    public function lists(){
        $params = $this->request->post();
        $where = [
            'user_id' => $this->auth->id
        ];
        if(isset($params['status']) && $params['status']){
            $where['status'] = $params['status'];
        }
        $lists = StaffOrderModel::where($where)->with(['job'=>function($query) use ($params) {
                $field = ' id, addr, lat, lng, mobile, student, sex, grade, subject, state, learn_date, learn_time, teacher_sex, teacher_type, demand, status';
                return $query->withField($field);
            }])->paginate(10);
        $this->success('', $lists);
    }

    //该岗位已经报名的家教列表
    public function lists_for_job()
    {
        $param = $this->request->param();
        $where = [];

        if(!isset($param['job_id']) || empty($param['job_id'])){
            $this->error('参数错误');
        }
        $where['job'] = $param['job_id'];

        $StaffModel = new StaffOrderModel();
        $lists = $StaffModel->where($where)->with('user')->paginate(10);

        $this->success('',$lists);
    }

    //家长觉得家教没问题，接受该申请
    public function pass()
    {
        $param = $this->request->param();

        Db::startTrans();
        try{
            if(!isset($param['order_id']) || !$param['order_id']){
                throw new \Exception('参数错误');
            }

            $order = (new StaffOrderModel())->where([
                'id' => $param['order_id'],
            ])->find();

            if(!$order){
                throw new \Exception('数据错误');
            }

            if($order['status']!==1){
                throw new \Exception('订单状态错误');
            }

            //作为家长发布的急招,确保这是属于能处理的数据
            $my_jobs = (new TeacherJobModel())->where([
                'user_id' => $this->auth->id,
                'id' => $order['job_id']
            ])->find();

            if(!$my_jobs){
                throw new \Exception('权限错误');
            }

            (new TeacherJobModel())->where([
                'user_id' => $this->auth->id,
                'id' => $order['job_id']
            ])->update([
                'status' => 3,
                'updatetime' => time()
            ]);

            $order->status = 2;
            $order->save();


            $params = $order['job_id'];
            //未被录用的家教退款
            \think\Hook::listen('xykeep_job_refund_all', $params);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }



        $this->success('操作成功');
    }

    //家长不喜欢这个老师，拒绝他的接单申请
    public function refuse()
    {
        $param = $this->request->param();

        Db::startTrans();
        try{
            if(!isset($param['order_id']) || !$param['order_id']){
                $this->error('参数错误');
            }

            $order = (new StaffOrderModel())->where([
                'id' => $param['order_id'],
            ])->find();

            if(!$order){
                $this->error('数据错误');
            }

            if($order['status']!==1){
                $this->error('订单状态错误');
            }

            //作为家长发布的急招,确保这是属于能处理的数据
            $my_jobs = Db::name('teacher_job')->where([
                'user_id' => $this->auth->id,
                'id' => $order['job_id']
            ])->find();

            if(!$my_jobs){
                $this->error('急招数据错误');
            }

            $order->refundtime = time();
            $order->status = -2;
            $order->save();

            $params['order'] = $order;
            $params['type'] = 'staff';
            \think\Hook::listen('xykeep_order_refund_after', $params);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('操作成功');
    }


    //家长提交评价
    public function boss_eva()
    {
        $param = $this->request->post();
        $user_id = $this->auth->id;

        $param['user_id'] = $user_id;
        $staff_order = (new StaffOrderModel())->where([
            'id' => $param['order_id'],
        ])->find();

        if($staff_order['boss_eva']){
            $this->error('你已经评价过了');
        }

        $param['teacher_id'] = $staff_order['user_id'];

        //判断有没有权限
        $my_jobs = Db::name('teacher_job')->where([
            'user_id' => $this->auth->id,
            'id' => $staff_order['job_id']
        ])->find();

        if($my_jobs){
            $this->error('您没有权限');
        }

        $validate = new CommentValidate();
        if (!$validate->scene('add')->check($param)) {
            $this->error($validate->getError());
        }

        Db::startTrans();
        try{

            $commentModel = new Comment();
            $comment_insert = [
                'user_id' => $user_id,
                'teacher_id' => $param['teacher_id'],
                'order_id' => $param['order_id'],
                'star' => $param['star'],
                'content' => $param['content'],
                'type' => 'staff'
            ];

            $commentModel->save($comment_insert);

            $staff_order->boss_eva = time();
            $staff_order->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('评论成功');
    }


    //完成订单-下班
    public function overOrder()
    {
        $params = $this->request->post();

        try{
            Db::startTrans();
            $detail = (new StaffOrderModel())->where([
                'user_id' => $this->auth->id,
                'id' => $params['order_id'],
            ])->find();

            if(!$detail){
                throw new \Exception('数据错误');
            }

            $jobData = (new TeacherJobModel())->where([
                'id' => $detail['job_id'],
            ])->find();

            if(!$jobData || $jobData['status']!==3){
                throw new \Exception('数据错误');
            }

            if($jobData['agreetime']){
                $jobData->status = 4;
                $jobData->refundtime = time();
                $jobData->save();
                //家长退款
                $params['order'] = $jobData;
                $params['type'] = 'job';
                \think\Hook::listen('xykeep_order_refund_after', $params);
            }

            $detail->status = 3;
            $detail->save();


            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('操作成功');
    }

    //教师取消急招接单
    public function cancel_order()
    {
        $params = $this->request->post();

        try{
            Db::startTrans();

            $staffOrder = (new StaffOrderModel())->where([
                'user_id' => $this->auth->id,
                'status' => ['in','1,2'],
                'job_id' => $params['id'],
            ])->find();

            if(!$staffOrder){
                throw new \Exception('数据错误');
            }

            if($staffOrder['status']==1){
                //家教退款
                $staffOrder->refundtime = time();
                $params['order'] = $staffOrder;
                $params['type'] = 'staff';
                \think\Hook::listen('xykeep_order_refund_after', $params);
            }

            $staffOrder->status = -1;
            $staffOrder->save();

            if($staffOrder['status']==2){
                //只有锁定了，才会影响家长发布的急招
                $teacherJob = (new TeacherJobModel())->where([
                    'id' => $params['id'],
                ])->find();

                $teacherJob->status = -1;
                $teacherJob->refundtime = time();
                $teacherJob->save();

                //家长退款
                $params['order'] = $teacherJob;
                $params['type'] = 'job';
                \think\Hook::listen('xykeep_order_refund_after', $params);
            }


            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('操作成功');
    }

    //申请平台介入
    public function platformIntervention()
    {
        $params = $this->request->post();

        $detail = (new StaffOrderModel())->where([
            'user_id' => $this->auth->id,
            'id' => $params['order_id'],
            'status' => ['in','2,3']
        ])->find();

        if(!$detail){
            $this->error('数据错误');
        }

        $detail->normal = 0;
        $detail->save();

        $this->success('操作成功');
    }

}